package com.lx.jobParametersDemo;

import org.springframework.batch.core.*;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Map;

/**
 * Job参数初探
 * 1.JobParameters作用：在Job运行过程中，可以用来传递信息
 * 2.通过”key---->value”键值对的形式传入，在代码中我们通过get(“key”)来获取value值
 *
 * @author lixing
 * @date 2021/7/12 16:38
 */
@Configuration
public class JobParametersConfiguretion implements StepExecutionListener {

    @Autowired
    private JobBuilderFactory jobBuilderFactory;
    @Autowired
    private StepBuilderFactory stepBuilderFactory;

    private Map<String, JobParameter> parames;


    @Bean
    public Job MyParametersJobThree() {
        return jobBuilderFactory.get("MyParametersJobThree")
                .start(MyParametersJobStep3())
                .build();
    }

    private Step MyParametersJobStep3() {

        return stepBuilderFactory.get("MyParametersJobStep3")
                .listener(this)
                .tasklet(new Tasklet() {

                    @Override
                    public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception {
                        System.out.println("parame is: " + parames.get("info"));
                        return RepeatStatus.FINISHED;
                    }
                }).build();
    }

    @Override
    public void beforeStep(StepExecution stepExecution) {
        System.out.println(stepExecution.getStepName() + "运行之前...........");
        parames = stepExecution.getJobParameters().getParameters();
    }

    @Override
    public ExitStatus afterStep(StepExecution stepExecution) {
        System.out.println(stepExecution.getStepName() + "运行之完毕...........");
        return null;
    }

    /*@Autowired
    private JobLauncher jobLauncher;
    @Autowired
    private JobRegistry jobRegistry;

    public void test() throws JobParametersInvalidException, JobExecutionAlreadyRunningException, JobRestartException, JobInstanceAlreadyCompleteException, NoSuchJobException {
//        JobParametersBuilder jobParametersBuilder = new JobParametersBuilder();
//        jobParametersBuilder.addJobParameters(jobParameters);
        JobParameters jobParameters = new JobParameters();
        Map<String, JobParameter> map = jobParameters.getParameters();
        map.put("", new JobParameter(""));
        Job job = jobRegistry.getJob("xxx");
        jobLauncher.run(job, jobParameters);
    }*/
}